package com.wangyu.springsecuritydemo.service.impl;

import com.wangyu.springsecuritydemo.constant.RoleConstant;
import com.wangyu.springsecuritydemo.entity.primary.RoleEntity;
import com.wangyu.springsecuritydemo.entity.primary.UserEntity;
import com.wangyu.springsecuritydemo.repository.primary.UserRepository;
import com.wangyu.springsecuritydemo.service.RoleService;
import com.wangyu.springsecuritydemo.service.UserService;
import javax.transaction.Transactional;
import org.apache.commons.lang3.Validate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 用户服务层实现
 *
 * @author wangyu
 * @Date 2019/2/18 22:45
 * @Version 1.0
 **/
@Service("userService")
public class UserServiceImpl implements UserService {

  @Autowired
  private UserRepository userRepository;

  @Autowired
  private RoleService roleService;

  /**
   * 密码加密方式
   */
  private BCryptPasswordEncoder bCrypt = new BCryptPasswordEncoder();

  @Override
  public UserEntity findByUserName(String username) {
    Validate.notBlank(username, "用户名不能为空");
    return userRepository.findByUserName(username);
  }

  @Override
  @Transactional
  public boolean insert(UserEntity userEntity) {
    Validate.notNull(userEntity, "对象不能为空");
    String username = userEntity.getUserName();
    UserEntity user = userRepository.findByUserName(username);
    if (user != null) {
      return false;
    }
    userEntity.setPassword(encodedPassword(userEntity.getPassword()));
    userRepository.save(userEntity);
    RoleEntity roleEntity = new RoleEntity();
    roleEntity.setName(RoleConstant.ROLE_USER);
    roleService.insert(roleEntity);

    userRepository.insertRoles(userEntity.getId(), roleEntity.getId());
    return true;
  }

  private String encodedPassword(String password) {
    return bCrypt.encode(password);
  }
}
